
package org.movee.spring.data.hugegraph.repository;

import org.movee.spring.data.hugegraph.mapping.HugePersistentEntity;
import org.movee.spring.data.hugegraph.query.HugeOperations;
import org.movee.spring.data.hugegraph.repository.query.HugeEntityInformation;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Optional;

/**
 * 用户定义的每一个 repository interface，都会有一个相应的 SimpleGremlinRepository 实例来处理 repository 调用
 * SimpleGremlinRepository 内有一个 HugeEntityInformation 字段表示它响应的domain entity
 * @param <T>
 * @param <ID>
 */
@Slf4j
public class SimpleHugeRepository<T, ID> implements HugeRepository<T, ID> {

    private final HugeEntityInformation<T, ID> information;
    private final HugeOperations operations;


    // 在 GremlinRepositoryFactory 中调用这个构造器构造一个实例
    public SimpleHugeRepository(HugeEntityInformation<T, ID> information, HugeOperations operations) {

        this.information = information;
        this.operations = operations;

        HugePersistentEntity<?> persistentEntity = operations.getConverter().getMappingContext()
                .getPersistentEntity(information.getJavaType());
        operations.getSchemaInitiator().updateSchema(persistentEntity);
    }

    @Override
    public T save(T entity) {
        return operations.save(entity, information.getJavaType());
    }

    @Override
    public List<T> saveAll(Iterable<T> entities) {
        return operations.saveAll(entities, information.getJavaType());
    }

    @Override
    public void justSaveAll(Iterable<T> entities) {
        operations.justSaveAll(entities, information.getJavaType());
    }

    @Override
    public Optional<T> findById(ID id) {
        return Optional.ofNullable(operations.findById(id, information.getJavaType()));
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<T> findAllById(Iterable<ID> ids) {
        return operations.findAllById((Iterable<Object>) ids, information.getJavaType());
    }

    @Override
    public boolean existsById(ID id) {
        return operations.existsById(id, information.getJavaType());
    }

    @Override
    public void deleteById(ID id) {
        operations.deleteById(id, information.getJavaType());
    }

    @Override
    public void delete(T entity) {
        operations.delete(entity, information.getJavaType());
    }

    @Override
    @SuppressWarnings("unchecked")
    public void deleteAllById(Iterable<ID> ids) {
        operations.deleteAllById((Iterable<Object>) ids, information.getJavaType());
    }

    @Override
    public void deleteAll(Iterable<T> entities) {
        operations.deleteAll(entities, information.getJavaType());
    }
}

